
#include "util.h"


#define	IsLeapYear(yr)	(!((yr) % 400) || (((yr) % 100) && !((yr) % 4)))
#define	YearLength(yr)	(IsLeapYear(yr) ? 366 : 365)
#define	BEGYEAR	        1970     // UTC started at 00:00:00 January 1, 2000
#define	DAY             86400UL  // 24 hours * 60 minutes * 60 seconds

/*********************************************************************
 * @fn      UTIL_MonthLength
 *
 * @param   lpyr - 1 for leap year, 0 if not
 *
 * @param   mon - 0 - 11 (jan - dec)
 *
 * @return  number of days in specified month
 */
LOCAL u8_t UTIL_MonthLength( u8_t lpyr, u8_t mon )
{
	u8_t days = 31;

	if ( mon == 1 ){ // feb
		days = ( 28 + lpyr );
	}
	else{
		if ( mon > 6 ){// aug-dec
			mon--;
		}

		if ( mon & 1 ){
			days = 30;
		}
	}

	return ( days );
}




PUBLIC void delayus(u16_t value)
{
	while (value--){
		asm("nop");
	}
	return;
}

PUBLIC void delayms(u16_t value)
{
	u16_t j;
	for(;value>0; value--){
		for(j=0; j<1000; j++)
		asm("nop");
	}
	return;
}

PUBLIC void c51pause(void)
{
	REG8(ADDR_REG_DOCD_CTRL) = 1;
	return;
}

PUBLIC void xmemcpy(u8_t __xdata * dst, u8_t __xdata *src, u16_t len)
{
	while(len--){
		*dst++ = *src++;
	}
	return;
}

PUBLIC void xmemset(u8_t __xdata * dst, u8_t value, u16_t len)
{
	while(len--) {
		*dst++ = value;
	}
	return;
}


PUBLIC bool UTIL_IsTimeoutPeriod330usTickCnt(u32_t prevValue, u32_t timeoutValue)
{
	u32_t curValue = REG32_READ(ADDR_REG_CLKN) & 0xFFFFFFF;
	if(curValue < prevValue) {
		curValue |= 0x10000000;
	}
	if(timeoutValue <= (curValue - prevValue)) {
		return true;
	}
	else{
		return false;
	}
}


PUBLIC void UTIL_ConvertUTCTime( UTCTimeStruct *tm, u32_t secTime )
{
 	// calculate the time less than a day - hours, minutes, seconds
	u32_t day = secTime % DAY;
	tm->seconds = day % 60UL;
	tm->minutes = (day % 3600UL) / 60UL;
	tm->hour = day / 3600UL;

  	// Fill in the calendar - day, month, year
	u16_t numDays = secTime / DAY;
	tm->year = BEGYEAR;
	while ( numDays >= YearLength( tm->year)){
		numDays -= YearLength( tm->year );
		tm->year++;
	}

	tm->month = 0;
	while ( numDays >= UTIL_MonthLength( IsLeapYear( tm->year ), tm->month)){
		numDays -= UTIL_MonthLength( IsLeapYear( tm->year ), tm->month );
		tm->month++;
	}

	tm->day = numDays;
	return;
}

